<?php

/**
 * 搜索模块
 * ============================================================================
 * $Author: 王海龙 $
 * $Id: search.php 2015-08-13 王海龙 $
*/

define('IN_ECS', true);
require(dirname(__FILE__) . '/includes/init.php');

$smarty->assign('page_title',      $_CFG['shop_title']); // 首页页面标题
$smarty->assign('keywords',        $_CFG['shop_keywords']); // 首页SEO网站关键词
$smarty->assign('description',     $_CFG['shop_desc']); // 首页SEO网站描述

/* 旧的搜索词方式 */
if (!empty($_GET['encode'])) {
    $string = base64_decode(trim($_GET['encode']));
    if ($string !== false)
    {
        $string = unserialize($string);
        if ($string !== false)
        {
            /* 用户在重定向的情况下当作一次访问 */
            if (!empty($string['search_encode_time']))
            {
                if (time() > $string['search_encode_time'] + 2)
                {
                    define('INGORE_VISIT_STATS', true);
                }
            }
            else
            {
                define('INGORE_VISIT_STATS', true);
            }
        }
        else
        {
            $string = array();
        }
    }
    else
    {
        $string = array();
    }
    $_REQUEST = array_merge($_REQUEST, addslashes_deep($string));
}


/* 搜索词、品牌、分类 */
$q   = !empty($_REQUEST['keywords']) ? htmlspecialchars(trim($_REQUEST['keywords'])) : (!empty($_REQUEST['q']) ? htmlspecialchars(trim($_REQUEST['q'])) : '');
$b   = !empty($_REQUEST['brand']) ? intval($_REQUEST['brand']) : (!empty($_REQUEST['b']) ? trim($_REQUEST['b']) : 0);
$c   = !empty($_REQUEST['category']) ? intval($_REQUEST['category']) : (!empty($_REQUEST['c']) ? intval($_REQUEST['c']) : 0);
/* 排序 */
$sort = (isset($_REQUEST['sort']) && in_array(trim(strtolower($_REQUEST['sort'])), array('buy_sum', 'sort_orders', 'sort_order', 'area_price', 'last_update', 'click_count'))) ? trim($_REQUEST['sort'])  : "sort_orders";

/*淘蛋产品默认最后  */
$sorts = ' g.is_taodan ASC, ' ;
if($sort == 'area_price'){
    $sorts .= '(g.shop_price)';
}elseif($sort == 'buy_sum'){
    $sorts .= '(g.click_count)';
}else{
    $sorts .= $sort;
}
$order = (isset($_REQUEST['order']) && in_array(trim(strtoupper($_REQUEST['order'])), array('ASC', 'DESC'))) ? trim($_REQUEST['order']) : 'ASC';

/**
 * 初始化搜索条件
 * 环境判断【品牌(可多选)】【分类(单选)】
 */
$where = "g.is_on_sale = 1 AND g.is_alone_sale = 1 AND warn_number = 1";
/* 如果存在品牌筛选 */
if (!empty($b)) {
    $bArr = explode(':', $b);
    foreach ($bArr as $key => $value) {
        $value = intval($value);
        if (empty($value)) {
            unset($bArr[$key]);
        }
    }
    if (!empty($bArr)) {
        $where .= " AND g.brand_id IN(" . implode(',', $bArr) . ")";
    }
}
/* 如果存在分类筛选 */
if (!empty($c)) {
    /* 获取所有子类 */
    $cArr = getCatAllChildren($c);
    $cArr[] = $c; // 将当前选择分类ID加进条件数组
    if (!empty($cArr)) {
        $cStr = implode(',', $cArr);
        /* 获取所有包含这些分类的goods_id */
        $sql = "SELECT goods_id FROM egg_goods_cat WHERE cat_id IN ($cStr)";
        $gArr = $db->getCol($sql);
        if (!empty($gArr)) {
            $gStr = implode(',', $gArr);
            $where .= " AND (g.cat_id IN($cStr) OR g.goods_id IN($gStr))";
        } else {
            $where .= " AND g.cat_id IN($cStr)";
        }
    }
} else {
    // 初始化可筛选分类ID
    $c = 600;
}

/* 检查搜索字符是否存在于词库 */
$kArr = formatKeyword($_REQUEST['keywords']);
$kArr = $kArr ? array_values($kArr) : array($q);
if (!empty($kArr)) {
    foreach ($kArr as $key => $value) {
        $where .= " AND CONCAT(g.goods_name, g.keywords, g.goods_desc, g.goods_brief) LIKE '%$value%'";
    }
}
/* 获取符合条件的所有商品ID */
$sql   = "SELECT goods_id FROM egg_goods AS g WHERE $where";
$goodsIdArr = $db->getCol($sql);

if (!empty($goodsIdArr)) {
    /* 查询语句 */
    $goodsIdStr = implode(',', $goodsIdArr);
    /* 获取总数 */
    $count = count($goodsIdArr);
    $size = 35;
    /* 设置当前页码 */
    $page       = !empty($_REQUEST['page']) && intval($_REQUEST['page'])  > 0 ? intval($_REQUEST['page'])  : 1;
    $maxPage = ($count> 0) ? ceil($count / $size) : 1;
    if ($page > $maxPage)
    {
        $page = $maxPage;
    }

    /* 获取可筛选分类信息 ----- */
    /* 获取所有分类ID */
    $catArr1 = $db->getCol("SELECT cat_id FROM egg_goods AS g WHERE goods_id IN($goodsIdStr)");
    $catArr2 = $db->getCol("SELECT cat_id FROM egg_goods_cat AS g WHERE goods_id IN($goodsIdStr)");
    $catArr = array_merge($catArr1, $catArr2);
    if ($catArr) {
        /* 获取当前所有有关父级分类 */
        $catArr2 = getCatAllParent($catArr);
        if ($catArr2) {
            $catArr = array_merge($catArr, $catArr2);
        }
    }
    $catStr = implode(',', $catArr);
    /* 获取可筛选分类信息 */
    $sql = "SELECT cat_id, cat_name FROM egg_category WHERE cat_id IN ($catStr) AND is_show = 1 AND parent_id = $c ORDER BY sort_order ASC";
    $catList = $db->getAll($sql);
    foreach ($catList as $key => $value) {
        $catList[$key]['url'] = getUrl('search', array('c'=>$value['cat_id'], 'b'=>$b, 'q'=>$q));
    }
    $smarty->assign('catList', $catList);

    /* 获取可筛选品牌信息 */
    if (empty($b)) {
        /* 获取当前所有品牌ID */
        $brandArr = $db->getCol("SELECT brand_id FROM egg_goods AS g WHERE goods_id IN($goodsIdStr)");
        $brandStr = implode(',', $brandArr);
        if ($brandStr) {
            $sql = "SELECT brand_id, brand_name, brand_logo FROM egg_brand WHERE brand_id IN ($brandStr) AND is_show = 1 ORDER BY sort_order ASC";
            $brandList = $db->getAll($sql);
        }
        foreach ($brandList as $key => $value) {
            $brandList[$key]['brand_logo'] = getUrl('brand_logo', $value['brand_logo']);
            $brandList[$key]['url'] = getUrl('search', array('c'=>$c, 'b'=>$value['brand_id'], 'q'=>$q));
        }
        $smarty->assign('brandList', $brandList);
    }
    /* 查询商品 */
    $sql = "SELECT g.goods_id, g.shopall_note, g.goods_name, g.market_price, g.shop_price, g.preferential_price2, 
            g.preferential_price5, g.click_count, g.promote_price, g.promote_start_date, g.promote_end_date, 
            g.goods_thumb, g.goods_img, g.goods_type, g.is_new, g.is_taodan, g.is_taobao 
            FROM egg_goods g WHERE g.goods_id IN($goodsIdStr) ORDER BY $sorts $order";
    echo $sql;
    $res = $db->SelectLimit($sql, $size, ($page - 1) * $size);
    $goodsList = array();
    while ($row = $db->FetchRow($res))
    {
        $goodsList[$row['goods_id']] = $row;
        if ($row['promote_price'] > 0)
        {
            $promote_price = bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']);
        }
        else
        {
            $promote_price = 0;
        }
        if($row['market_price'] > 0){//当存在市场价的时候的市场价
            $goodsList[$row['goods_id']]['market_price']    = price_format(sprintf('%.1f',$row['market_price']));
        }else{//不存在市场价的时候的市场价
            $goodsList[$row['goods_id']]['market_price']    = price_format(sprintf('%.1f',($row['shop_price'])*1.2));
        }
        $goodsList[$row['goods_id']]['shop_price']          = price_format($row['shop_price']);
        $goodsList[$row['goods_id']]['promote_price']       = ($promote_price > 0) ? price_format($promote_price) : '';
        $goodsList[$row['goods_id']]['goods_thumb']         = getUrl('goods_thumb', $row['goods_thumb']);
        $goodsList[$row['goods_id']]['goods_img']           = getUrl('goods_img', $row['goods_img']);
        $goodsList[$row['goods_id']]['url']                 = getUrl('goods', $row);
        $goodsList[$row['goods_id']]['thumb_list']          = get_thumb($row['goods_id']);
        $goodsListIdArr[] = $row['goods_id'];
    }
    /* 查询是否有货和销量 */
    if (!empty($goodsList)) {
        $goodsListIdStr = implode(',', $goodsListIdArr);
        /* 销量 */
        $sql = "SELECT goods_id, sum(goods_number) AS salse FROM egg_order_goods WHERE goods_id IN($goodsListIdStr) GROUP BY goods_id";
        $res = $db->query($sql);
        while ($row = $db->FetchRow($res))
        {
            $goodsList[$row['goods_id']]['salse'] = $row['salse'];
        }
        /* 是否有货 */
        $sql = "SELECT goods_id, sum(goods_number) AS stock FROM egg_goods_stock WHERE goods_id IN($goodsListIdStr) GROUP BY goods_id";
        $res = $db->query($sql);
        while ($row = $db->FetchRow($res))
        {
            if ($row['stock'] > 0) {
                $goodsList[$row['goods_id']]['stock'] = $row['stock'];
            }
        }
    }
    $smarty->assign('goodsList', $goodsList);
}

/* 获取产品列表底部广告 */
$smarty->assign('ad_1', get_ad(12));
$smarty->assign('goods_random',    category_get_goods_random()); // 获取随机查询的商品信息
$smarty->assign('goods_hot',       category_get_goods_hot()); // 获取热销产品
$smarty->assign('hot_goods',       get_recommend_goods('hot'));
$smarty->assign('keywords',   $_CFG['shop_keywords'].','.$q);
$smarty->assign('search_keywords',   $q);
$smarty->assign('q',   $q);
$smarty->assign('c',   $c);
$smarty->assign('b',   $b);

/* 分页 */
$pager['search'] = array(
    'q'      => $q,
    'c'      => $c,
    'b'      => $b,
    'sort'   => $sort,
    'order'  => $order,
    'action' => $action,
);
$pager = get_pager('search.php', $pager['search'], $count, $page, $size);
$smarty->assign('crumb', getCrumb($c, $b, $q));
$smarty->assign('pager', $pager);
$smarty->display('search.dwt');

/**
 * 格式化当前搜索词
 * @param  str $keywords 搜索字符串
 * @return arr           词组
 */
function formatKeyword($keywords)
{
    /* 查询当前词库 */
    $sql = " SELECT value FROM " . $GLOBALS['ecs']->table('shop_config') . " WHERE code = 'word' ";
    $word = explode(',', $GLOBALS['db']->getOne($sql));
    if($keywords){
        for($i=0;$i<mb_strlen($keywords,'UTF8');$i++){
            for ($j=$i+1; $j <= mb_strlen($keywords,'UTF8'); $j++) { 
                $k = mb_substr($keywords,$i,$j-$i,'UTF8');
                if(in_array($k,$word)){
                    $word_arr[] = $k;
                }
            }
        }
    }
    $len = count($word_arr);
    for($i=0;$i<$len;$i++){
        for($j=$i+1;$j<$len;$j++){
            if(mb_strlen($word_arr[$i],'UTF8')<mb_strlen($word_arr[$j],'UTF8')){
                $tmp=$word_arr[$j];
                $word_arr[$j]=$word_arr[$i];
                $word_arr[$i]=$tmp;
            }
        }
    }
    return $word_arr;
}

/**
 * 获得广告位
 *
 * @access  private
 * @return  array
 */
function get_ad($position_id = 0){
        if(!$position_id) return false;
        $position_id = intval($position_id);
        $sql = "SELECT * FROM " . $GLOBALS['ecs']->table('ad') . " WHERE position_id = '$position_id' ORDER BY ad_name ASC ";
        return $GLOBALS['db']->getAll($sql);
    }

/**
 * 获得热销的商品
 *
 * @access  public
 * @param   string  $children
 * @return  array
 */
function category_get_goods_hot()
{
    $sql = 'SELECT g.goods_id, g.goods_name, g.shop_price, g.promote_price, g.goods_thumb , g.goods_img, g.is_hot, ' . 
        "(select count(1) from " . $GLOBALS['ecs']->table('comment') . " WHERE goods_id = g.goods_id) as counts " . 
        ' FROM '. $GLOBALS['ecs']->table('goods') . 'AS g ' . 
        " WHERE g.is_hot = 1 AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 LIMIT 13";    
    $res = $GLOBALS['db']->query($sql);
    $arr = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $arr[$row['goods_id']]['goods_id']         = $row['goods_id'];
        $arr[$row['goods_id']]['goods_name']       = $row['goods_name'];
        $arr[$row['goods_id']]['shop_price']       = price_format($row['shop_price']);
        $arr[$row['goods_id']]['goods_thumb']      = get_image_path($row['goods_id'], $row['goods_thumb'], true);
        $arr[$row['goods_id']]['goods_img']        = get_image_path($row['goods_id'], $row['goods_img']);
        $arr[$row['goods_id']]['url']              = build_uri('goods', array('gid'=>$row['goods_id']), $row['goods_name']);
        $arr[$row['goods_id']]['is_hot']           = $row['is_hot'];
        $arr[$row['goods_id']]['counts']           = $row['counts'];
    }
    return $arr;
}

/**
 * 获得随机查询的商品
 *
 * @access  public
 * @param   string  $children
 * @return  array
 */
function category_get_goods_random()
{
    $sql = 'SELECT g.goods_id, g.goods_name, g.shop_price, g.promote_price, g.goods_thumb , g.goods_img, ' . 
        "(select count(1) from " . $GLOBALS['ecs']->table('comment') . " WHERE goods_id = g.goods_id) as counts " . 
        ' FROM ' . $GLOBALS['ecs']->table('goods') . ' AS g ' .  
        " WHERE g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 ORDER BY RAND() LIMIT 15";
    $res = $GLOBALS['db']->query($sql);
    
    $arr = array();
    $i=0;
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $arr[$i]['goods_id']         = $row['goods_id'];
        $arr[$i]['goods_name']       = $row['goods_name'];
        $arr[$i]['shop_price']       = price_format($row['shop_price']);
        $arr[$i]['goods_thumb']      = get_image_path($row['goods_id'], $row['goods_thumb'], true);
        $arr[$i]['goods_img']        = get_image_path($row['goods_id'], $row['goods_img']);
        $arr[$i]['url']              = build_uri('goods', array('gid'=>$row['goods_id']), $row['goods_name']);
        $arr[$i++]['counts']         = $row['counts'];
    }
    return $arr;
}

/**
 * 获取面包屑信息
 * @param  int $c 分类ID
 * @param  str $b 品牌筛选
 * @param  str $q 搜索词
 * @return arr    面包屑信息
 */
function getCrumb($c, $b, $q) {
    $data = array();
    if (!empty($c)) {
        /* 获取当前分类信息 */
        $sql = "SELECT cat_id, cat_name AS name, parent_id FROM egg_category WHERE cat_id = $c";
        $row = $GLOBALS['db']->getRow($sql);
        $row['url'] = getUrl('search', array('c'=>$row['cat_id'], 'b'=>$b, 'q'=>$q));
        $cArr[] = $row;
        while (!empty($row['parent_id'])) {
            $sql = "SELECT cat_id, cat_name AS name, parent_id FROM egg_category WHERE cat_id = {$row['parent_id']}";
            $row = $GLOBALS['db']->getRow($sql);
            $row['url'] = getUrl('search', array('c'=>$row['cat_id'], 'b'=>$b, 'q'=>$q));
            $cArr[] = $row;
        }
        if (!empty($cArr)) {
            $data = array_reverse($cArr);
        }
        unset($row);
    }
    if (!empty($b)) {
        /* 获取当前品牌信息 */
        $str = str_replace(':', ',', $b);
        $sql = "SELECT brand_name AS name FROM egg_brand WHERE brand_id IN ($str)";
        $arr = $GLOBALS['db']->getCol($sql);
        $row['name'] = implode('、', $arr);
        $row['url'] = getUrl('search', array('c'=>$c, 'b'=>'', 'q'=>$q));
        $row['crumbAttr'] = true;
        $data[] = $row;
    }
    return $data;
}
